import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtIcon} from "taro-ui";
import {View, Image, Text, Block} from '@tarojs/components'
import {http} from '../../utils/http'
import {SELECT_CAR_RENTAL_OUT_LETS, RESOURCE_URL, SELECT_CAR_RENTAL} from '../../constants/api'
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import {location as locationServer} from "../../utils/location.service";
import CityLocation from "../components/city-search-location/city-search-location";
import './list.scss'

type pageState = {
  loadMoreStatus: any
  listData: any
  layOutInfo: any
  layIndex: any
  name: any
}

export default class List extends Component {
  state: pageState = {
    loadMoreStatus: 'loading',
    listData: [],
    layOutInfo: {},
    name: '',
    layIndex: 0
  }

  async UNSAFE_componentWillMount() {
    const city = Taro.getStorageSync('city')
    if (city && city.area_name) {
      this.areaName = city.area_name
    }
    await vcmonitor(this)
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    await this.location()
  }

  async componentDidShow() {
    let areaName = ''
    const city = Taro.getStorageSync('city')
    if (city && city.area_name) {
      areaName = city.area_name
    }
    if (this.areaName !== areaName) {
      this.areaName = areaName
      this.page = 1
      this.total = 0
      this.setState({loadMoreStatus: 'loading', listData: await this.getData(this.page)})
    }
    Taro.setNavigationBarTitle({title: '车型列表'})
  }

  page = 1
  total = 0
  areaName

  async location() {
    if (!Taro.getStorageSync('locationData')) {
      locationServer.getLocation().then(async (res: any) => {
        if (res) {
          Taro.setStorageSync('locationData', res);
        }
        this.setState({listData: await this.getData(this.page)})
      })
    } else {
      this.setState({listData: await this.getData(this.page)})
    }
  }

  async getData(page) {
    const listData = await http.carGet(SELECT_CAR_RENTAL_OUT_LETS, {page, size: 10, name: this.state.name})
    listData.list.map(item => {
      item.readMore = false
      item.modelList = []
    })
    this.total = listData.totalPage
    if (this.page * 10 < this.total) {
      this.setState({loadMoreStatus: 'more'})
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    return listData.list || []
  }

  onReachBottom() {
    const loadMoreStatus = this.state.loadMoreStatus
    if (loadMoreStatus != 'noMore' && loadMoreStatus != 'loading') {
      this.setState({loadMoreStatus: 'loading'}, async () => {
        this.page++
        const listData = await this.getData(this.page)
        const old = this.state.listData
        this.setState({listData: [...old, ...listData]})
      })
    }
  }

  async readMoreChange(index, num) {
    if (!num) {
      return false
    }
    const {listData} = this.state
    const i = listData.findIndex(item => item.readMore)
    if (i > -1 && index !== i) {
      listData[i].readMore = !listData[i].readMore
    }
    this.setState({listData}, async () => {
      if (listData[index].modelList.length <= 0) {
        await Taro.showLoading({title: '加载中...'})
        const modelData = await http.carGet(SELECT_CAR_RENTAL, {page: 1, size: 9999, branch_id: listData[index].id})
        modelData.list.map(item => {
          const config = []
          if (item.displacement) {
            config.push(item.displacement)
          }
          if (item.gear) {
            config.push(item.gear)
          }
          if (item.seat_nums) {
            config.push(item.seat_nums + '座')
          }
          item.config = config.join(' | ')
        })
        listData[index].modelList = modelData.list
        Taro.hideLoading()
      }
      listData[index].readMore = !listData[index].readMore
      this.setState({layIndex: index, layOutInfo: listData[index], listData})
    })
  }

  handleClose() {
    const {listData, layIndex} = this.state
    listData[layIndex].readMore = !listData[layIndex].readMore
    this.setState({listData})
  }

  async callBackOnActionClick() {
    this.page = 1
    this.setState({listData: await this.getData(this.page)})
  }

  onChange(name) {
    this.setState({name})
  }

  onClear() {
    this.setState({name: ''}, async () => {
      await this.callBackOnActionClick()
    })
  }

  render() {
    const {listData, loadMoreStatus, layOutInfo} = this.state
    return (
      <View className='carRentalList'>
        <GzhAuth />
        <View className='car-search'>
          <CityLocation areaName={this.areaName} onConfirm={this.callBackOnActionClick.bind(this)}
            onChange={this.onChange.bind(this)} onClear={this.onClear.bind(this)} maxLength={50}
          />
        </View>
        {listData && listData.length > 0 && <View className='car-list-box'>
          {listData.map((item, index) => <View key={item.uuid} className='car-list-item'>
            <View style='margin: 0 15px;'>
              {!!item.name && <View className='car-title'
                onClick={() => Taro.navigateTo({url: '/other/carRental/outletsDetail?uuid=' + item.uuid})}
              >
                <Text className='car-name'>{item.name}</Text>
                <AtIcon value='chevron-right' size='14' color='#000' customStyle='line-height: inherit;' />
              </View>}
              <View className='car-info' onClick={this.readMoreChange.bind(this, index, item.num)}>
                <View className='car-info-distance-time'>
                  {!!item.distance && <Text>{item.distance}</Text>}
                  {!!item.distance && !!item.business_hours_start && <Text className='car-info-line'>|</Text>}
                  {!!item.business_hours_start &&
                  <Text>{item.business_hours_start}-{item.business_hours_end}</Text>}
                </View>
                <View className='car-info-type'>
                  {!!item.num ? <Block>
                    {!item.readMore && <View className='view-inline'>{item.num}款车型可租</View>}
                    {item.readMore && <View className='view-inline'>收起</View>}
                    <Text className={`triangle ${item.readMore && 'triangle-top'}`} />
                  </Block> : <View className='view-inline'>暂无车型可租</View>}
                </View>
              </View>
            </View>
            {item.readMore && layOutInfo.modelList && layOutInfo.modelList.length > 0 && <View className='car-list-box'>
              <View className='carRentalDetailWrapper'>
                {layOutInfo.modelList.map(items => <View key={items.uuid} key={items.uuid}
                  className='car-list-item car-list-item-detail'
                  onClick={() => {
                                                           Taro.navigateTo({url: `/other/carRental/detail?uuid=${items.uuid}`})
                                                         }}
                >
                  <View className='car-info-detail'>
                    <Image className='car-info-detail-left' src={items.photos} mode='aspectFill' />
                    <View className='car-info-detail-right'>
                      {!!items.name && <View className='car-title'>
                        <Text className='car-name car-big-name'>{items.name}</Text>
                      </View>}
                      <View className='car-config-info'>
                        <View className='car-config-intro'>
                          {items.config || ''}
                        </View>
                        <View className='price-box'><Text className='car-symbol'>￥</Text><Text
                          className='car-price'
                        >{items.per_price}</Text><Text className='car-unit'>日均</Text></View>
                      </View>
                      <View className='go-car-detail'>车型详情<AtIcon value='chevron-right' size='12' color='#333'
                        customStyle='line-height: inherit;font-weight: bold;'
                      /></View>
                    </View>
                  </View>
                </View>)}
              </View>
            </View>}
          </View>)}
        </View>}
        {loadMoreStatus !== 'loading' && listData && listData.length <= 0 &&
        <View className='listNull'>
          <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
          <View className='text'>什么都没有,去看看别的吧~</View>
        </View>
        }
      </View>
    )
  }
}
